import {
  createRouter,
  createWebHistory,
  createWebHashHistory
} from 'vue-router'
import store from '../store';
import routes from '../router/router.js'






const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  base: '/admin',
  routes
});
const getManageIndex ={
    testAuthNav(name) {
      let isShow = false;
      store.state.authList.forEach(t => {
        if (t.pc_url.indexOf(name) != -1) {
          isShow = true;
        }
      })
      return isShow
    },
    manageIndexPath() {
      for(let i in navs){
        let item = navs[i];
        if(getManageIndex.testAuthNav(item.name)){
          if(item.children && item.children.length > 0){
            for(let j in item.children){
              let t = item.children[j];
              if(getManageIndex.testAuthNav(t.name)){
                return t.path;
              }
            }
          }
          return item.path;
        }
      }
      return ''
    }
}

router.beforeEach(async (to, from, next) => {
  if(to.path == '/' || to.path == '') {
    next('/administrators')
    return
  }
  
  if(to.matched.length == 0 && (to.path != '/' || to.path != '/administrators')) {
    next('/view404')
    return
  }
  
  if(to.fullPath == '/view404' || to.fullPath == '/view403' || to.fullPath == '/camera') {
    next()
    return
  }
  
  if(to.path == '/login') {
    if(store.state.token) {
      next('/administrators')
    } else {
      next()
    }
    return
  }
  
  // 如果没有token，跳转到登录页
  if(!store.state.token) {
    next('/login')
    return
  }
  
  // 检查用户信息是否存在
  if(!store.state.userInfo && !localStorage.getItem('userInfo')) {
    next('/login')
    return
  }
  
  // 特殊处理administrators路由
  if(to.name === 'administrators') {
    next()
    return
  }
  
  // 获取用户菜单列表
  const menuList = store.state.userInfo?.menu_list || []
  
  // 检查是否有权限访问目标路由
  const hasPermission = menuList.some(item => {
    // 检查当前路由是否匹配菜单项或其子项
    const isMatch = item.name === to.name || item.path === to.path
    
    // 检查子菜单
    const hasChildAccess = item.children?.some(child => 
      child.name === to.name || child.path === to.path
    )
    
    return isMatch || hasChildAccess
  })
  
  // 如果有权限或者是在开发环境，则放行
  if(hasPermission || process.env.NODE_ENV === 'development') {
    next()
  } else {
    // 否则跳转到403页面
    next('/view403')
  }
})

export default router
